import { defineNuxtPlugin } from "nuxt/app";
import geoip from "geoip-lite";
import { useGlobalStore } from "~~/store/global";
import { nation } from "~/config/nation";

export default defineNuxtPlugin({
  name: "ip-plugin",
  parallel: true,
  setup() {
    const globalStore = useGlobalStore();
    const requestEvent = useRequestEvent();

    {
      //  1. 先通过nginx传递的ip来获取用户的真实ip
      const nginxSecurityIp =
        requestEvent?.node.req?.headers["nginx-security-ip"];
      const xForwardedFor = requestEvent?.node.req?.headers["x-forwarded-for"];
      const xRealIp = requestEvent?.node.req?.headers["Nginx-Security-Ip"];
      let publicIp: string | undefined = undefined;

      if (typeof nginxSecurityIp === "string") {
        if (nginxSecurityIp.includes(",")) {
          const list = nginxSecurityIp.split(",");

          if (list.length > 0) {
            publicIp = list[list.length - 1]?.trim();
          }
        } else {
          publicIp = nginxSecurityIp;
        }
      }

      globalStore.nginxSecurityIp = nginxSecurityIp;
      globalStore.xForwardedFor = xForwardedFor;
      globalStore.xRealIp = xRealIp;
      globalStore.publicIp = publicIp;
    }

    {
      // 2. 再通过ip获取用户的地理位置
      try {
        if (globalStore.publicIp) {
          const geo = geoip.lookup(globalStore.publicIp);

          globalStore.geo = geo ?? undefined;

          if (globalStore.geo) {
            const find = Object.keys(nation).find(
              (key) =>
                key.toLocaleLowerCase() ===
                globalStore.geo?.country?.toLocaleLowerCase()
            ) as keyof typeof nation;

            if (find) {
              globalStore.publicArea = nation[find].dialCode;
            }
          }
        }
      } catch (e) {
        console.error(e);
      }
    }
  },
});
